﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jbe.TestSuite.RtfEditor.Domain;
using Jbe.TestSuite.Infrastructure.Interface.Documents;
using Microsoft.Practices.Composite.Regions;
using Jbe.TestSuite.Infrastructure.Interface;
using System.Collections.Specialized;
using Jbe.Composite.Extensions;

namespace Jbe.TestSuite.RtfEditor.Applications
{
    internal class DocumentController : DocumentController<RichTextDocument>, IActiveDocumentProvider
    {
        private readonly IApplicationContainer container;
        private readonly IDocumentManager documentManager;
        private readonly IRegion contentRegion;
        private readonly List<RichTextEditorPresentationModel> presentationModels;


        public DocumentController(IApplicationContainer container, IDocumentManager documentManager, IRegionManager regionManager)
            : base(documentManager)
        {
            this.container = container;
            this.documentManager = documentManager;
            this.contentRegion = regionManager.Regions[ShellRegionNames.ContentRegion];
            this.presentationModels = new List<RichTextEditorPresentationModel>();
        }


        public void Initialize()
        {
            documentManager.Register(this);
        }

        public Document GetActiveDocument()
        {
            object view = contentRegion.ActiveViews.Count() == 1 ? contentRegion.ActiveViews.First() : null;
            if (view != null)
            {
                RichTextEditorPresentationModel presentationModel = presentationModels.SingleOrDefault(pm => pm.View == view);
                if (presentationModel != null)
                {
                    return presentationModel.Document;
                }
            }
            return null;
        }

        protected override void DocumentAdded(RichTextDocument document)
        {
            IRichTextEditorView view = container.Resolve<IRichTextEditorView>();
            RichTextEditorPresentationModel presentationModel = new RichTextEditorPresentationModel(view, document);
            presentationModels.Add(presentationModel);
            contentRegion.Add(presentationModel.View);
        }

        protected override void DocumentRemoved(RichTextDocument document)
        {
            RichTextEditorPresentationModel presentationModel = presentationModels.Single(pm => pm.Document == document);
            presentationModels.Remove(presentationModel);
            contentRegion.Remove(presentationModel.View);
        }

        protected override void ActiveDocumentChanged(RichTextDocument activeDocument)
        {
            RichTextEditorPresentationModel presentationModel = presentationModels.Single(pm => pm.Document == activeDocument);
            contentRegion.Activate(presentationModel.View);
        }
    }
}
